package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.CommentModel;
import com.jtech.together.model.TrendsModel;
import com.jtech.together.model.event.TrendsEvent;
import com.jtech.together.mvp.contract.TrendsDetailContract;
import com.jtech.together.util.BmobUtil;
import com.jtech.together.util.Bus;
import com.jtech.together.view.activity.TrendsDetailActivity;

import java.util.Arrays;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 动态详情
 * Created by wuxubaiyang on 2017/5/16.
 */
public class TrendsDetailPresenter implements TrendsDetailContract.Presenter {
    private Context context;
    private TrendsDetailContract.View view;
    private String trendsId;

    public TrendsDetailPresenter(Context context, TrendsDetailContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
        //获取动态id
        if (null != bundle) {
            this.trendsId = bundle.getString(TrendsDetailActivity.KEY_TRENDS_ID, "");
        }
    }

    @Override
    public void loadTrends() {
        new BmobQuery<TrendsModel>()
                .include("user")
                .getObjectObservable(TrendsModel.class, trendsId)
                .subscribeOn(Schedulers.io())
                .map(new Func1<TrendsModel, TrendsModel>() {
                    @Override
                    public TrendsModel call(TrendsModel trendsModel) {
                        //处理喜欢集合
                        String myUserId = UserManager.getCurrentUserId();
                        for (String userId : trendsModel.getLikes()) {
                            if (myUserId.equals(userId)) {
                                trendsModel.setLikes(Arrays.asList(myUserId));
                                break;
                            }
                        }
                        //处理不喜欢人集合
                        for (String userId : trendsModel.getUnlikes()) {
                            if (myUserId.equals(userId)) {
                                trendsModel.setUnlikes(Arrays.asList(myUserId));
                                break;
                            }
                        }
                        return trendsModel;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TrendsModel>() {
                    @Override
                    public void call(TrendsModel trendsModel) {
                        view.loadTrendsSuccess(trendsModel);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        view.loadFail("加载失败，请重试");
                    }
                });
    }

    @Override
    public void loadComments(int pageIndex, int displayNumber, final boolean loadMore) {
        new BmobQuery<CommentModel>()
                .addWhereEqualTo("trends", new TrendsModel(trendsId))
                .setLimit(displayNumber)
                .setSkip(pageIndex * displayNumber)
                .order("-createdAt")
                .include("user")
                .findObjects(new FindListener<CommentModel>() {
                    @Override
                    public void done(List<CommentModel> list, BmobException e) {
                        if (null == e) {
                            view.loadCommentSuccess(list, loadMore);
                        } else {
                            view.loadFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                        }
                    }
                });
    }

    @Override
    public void publishComment(String content, final TrendsModel trendsModel) {
        final CommentModel commentModel = new CommentModel();
        commentModel.setUser(UserManager.getCurrentUser());
        commentModel.setTrends(new TrendsModel(trendsId));
        commentModel.setContent(content);
        commentModel.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (null == e) {
                    view.publishSuccess(commentModel);
                    //发送消息
                    Bus.get().post(new TrendsEvent(trendsId, TrendsEvent.STATE_COMMENT, 1));
                    //添加评论数
                    addCommentCount(trendsModel);
                } else {
                    view.publishFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }

    /**
     * 评论数加1
     *
     * @param trendsModel
     */
    private void addCommentCount(TrendsModel trendsModel) {
        trendsModel
                .addCommentCount()
                .update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                    }
                });
    }

    @Override
    public void like(final TrendsModel trendsModel, final int count) {
        trendsModel
                .like(UserManager.getCurrentUser(), count)
                .update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (null == e) {
                            view.operationSuccess(trendsModel);
                            //发送消息
                            Bus.get().post(new TrendsEvent(trendsModel.getObjectId(), TrendsEvent.STATE_LIKE, count));
                        } else {
                            view.operationFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                        }
                    }
                });
    }

    @Override
    public void unlike(final TrendsModel trendsModel, final int count) {
        trendsModel
                .unlike(UserManager.getCurrentUser(), count)
                .update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (null == e) {
                            view.operationSuccess(trendsModel);
                            //发送消息
                            Bus.get().post(new TrendsEvent(trendsModel.getObjectId(), TrendsEvent.STATE_UNLIKE, count));
                        } else {
                            view.operationFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                        }
                    }
                });
    }
}